package univer.oko.query.baseObjects;

import univer.oko.database.rmi.RMILogger;

/**
 * Created by Sergey Kharlamov.
 * Date: 09.04.2006
 * Time: 22:06:36
 */
public class View extends DBObject {

    public View() {
        type = DBObjectType.View;

    }

    public String getText() {
        return text;
    }

    public String getTextWithoutHeader() {
        return textWithoutHeader;
    }

    public void setTextWithoutHeader(String textWithoutHeader) {
        this.textWithoutHeader = textWithoutHeader;
        this.text = "CREATE VIEW " + name + " AS " + textWithoutHeader;
    }

    // "[(/\\*.*\\*/)|(--.*\\n)| |\\n|\\t|\\r]+"
    public void setText(String text) {
        this.text = text;
        String[] splited = text.substring(getStartedIndex(text)).trim().split("[ *|\\n*|\\t*|\\r*]+", 5);
        if (splited.length < 5)
            RMILogger.log(new Exception("Invalid view format"));
        name = splited[2];
        textWithoutHeader = splited[4];
    }

    private int getStartedIndex(String text) {
        boolean inBlockComment = false;
        boolean inLineComment = false;
        String str;
        for (int i = 0; i < text.length(); i++) {
            str = text.substring(i, i + 2);
            if (str.equals("/*"))
                inBlockComment = true;
            if (str.equals("*/"))
                inBlockComment = false;
            if (str.equals("--"))
                inLineComment = true;
            if (text.substring(i, i + 1).equals("\n"))
                inLineComment = false;

            if (text.substring(i, i + 6).equalsIgnoreCase("create") && !inBlockComment && !inLineComment)
                return i;
        }
        return 0;
    }


}
